package gr.aueb.mscis.chord;

import gr.aueb.mscis.utils.Sha1;

import java.math.BigDecimal;
import java.math.BigInteger;

public class FingerAgent extends Thread {
	private Node node;

	public FingerAgent(Node node) {
		this.node = node;
	}

	public void run() {
		int counter = 0;
		while (!this.isInterrupted()) {
			while (counter < 6) {
				
				if(counter == 0){
					Node.fingerTable[counter] = node.getSuccessor();
					continue;
				}
				
				BigInteger addition = (new BigDecimal(String.valueOf(Math.pow(2, (counter - 1))))).toBigInteger(); // how much we will add to our ID.
				Sha1 nodeIdSha = new Sha1(node.getNodeId().getHash(), true);
				String targetID = nodeIdSha.toString((new BigInteger(nodeIdSha.getByteArray())).add(addition).toByteArray()); // this.ID() + addition.

				node.find_successor(targetID, node.getNodeId(), counter);
				counter++;
			}

			/*SYNTHRHSH LISTAS DIADOXWN*/
			RemoteMessageAgent connect = new RemoteMessageAgent();
			connect.getSuccessors(this.node);	
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {e.printStackTrace();}
			
		}
		
	}
}
